package com.example.exam.sysRole.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.exam.sysPermission.entity.SysPermissionBean;
import com.example.exam.sysPermission.service.SysPermissionService;
import com.example.exam.sysResource.model.SysResourceBean;
import com.example.exam.sysResource.service.SysResourceService;
import com.example.exam.sysRoleResourcePermission.entity.SysRoleResourcePermissionBean;
import com.example.exam.sysRoleResourcePermission.service.SysRoleResourcePermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("dtree")
public class SysRoleDtreeController {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	private String base_path = "/sysRole/";
	
	@Autowired
	private SysRoleResourcePermissionService sysRoleresourcePerService;
	@Autowired
	private SysPermissionService permissionService;
	@Autowired
	private SysResourceService sysResourceService;
	@RequestMapping("/index")
	    /** 
	        * @Description:  去角色授权页面
	        * @Param: [request, roleId] 
	        * @return: java.lang.String 
	        * @Author: xhw
	        * @Date: 2021/7/26 
	        */ 
	public String toDtreePage(HttpServletRequest request, String roleId) {
		request.setAttribute("roleId", roleId);
		return base_path+"roleDtree";
	}
	@RequestMapping("getTreeList")
	    /** 
	        * @Description:查询权限树
		 	* 第一层父菜单
		 	* 第二层子菜单
		 	* 第三层权限表（用菜单角色权限表验证是否勾选）
	        * @Param: [request] 
	        * @return: java.lang.Object 
	        * @Author: xhw
	        * @Date: 2021/7/26 
	        */ 
	@ResponseBody
	public Object getTreeList(HttpServletRequest request) {
		String roleId = request.getParameter("roleId");
		List<Map<String, Object>> listResource = null;
		try {
			if (roleId!=null) {
				listResource = sysResourceService.getMenuListByRoleId(roleId);
			}
		} catch (Exception e) {
			e.getMessage();
			return null;
		}
		return JSON.toJSON(listResource);
	}

	/**
	 * 取消保存权限
	 * 勾选添加
	 * 不勾删除
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAdd")
	@ResponseBody
	    /** 
	        * @Description:取消保存权限
		 	*勾选添加
		 	* 不勾删除
	        * @Param: [request] 
	        * @return: java.lang.Object 
	        * @Author: xhw
	        * @Date: 2021/7/26 
	        */ 
	public Object saveGrant(HttpServletRequest request) {
		   Map<String,Object> maps = new HashMap<String,Object>();
		   try {
			  String roleId = request.getParameter("roleId");
			  String datas = request.getParameter("data");
			  if (datas!=null) {
				  JSONObject jsonObject = JSONObject.parseObject(datas);
				  Map<String, Object> map = jsonObject.getInnerMap();
				  Integer nodeId=Integer.parseInt(map.get("nodeId").toString());
				  Integer parentId=Integer.parseInt(map.get("parentId").toString());
				  List<SysPermissionBean> permissionBeans = null;
				  if(parentId == 1) {
					  permissionBeans = permissionService.queryPermissionList(nodeId);
				  }else {
					  permissionBeans = permissionService.queryPermissionList(parentId);
				  }
				  int count=0;
				  if(map.get("ischecked").toString().equals("0")) {
						  if(parentId==0) {
							  List<SysResourceBean> list = sysResourceService.queryResource(nodeId);
							  for (SysResourceBean srb : list) {
								Integer resource=srb.getId();
								permissionBeans = permissionService.queryPermissionList(resource);
								for (SysPermissionBean permission : permissionBeans) {
									 Integer node=permission.getId();
									 Integer parent=resource;
									 count += sysRoleresourcePerService.delDataByRoleId(Integer.parseInt(roleId),parent,node);	 
							    }
							  }
						  }else if(parentId==1) {
							  permissionBeans = permissionService.queryPermissionList(nodeId);
								for (SysPermissionBean permission : permissionBeans) {
									 Integer node=permission.getId();
									 Integer parent=nodeId;
									 count += sysRoleresourcePerService.delDataByRoleId(Integer.parseInt(roleId),parent,node);	 
							    }
						  }else{
							  count = sysRoleresourcePerService.delDataByRoleId(Integer.parseInt(roleId),parentId,nodeId);
						  }
					  if (count>0) {
						  maps.put("code", 1);
						  maps.put("msg", "取消授权成功！");
					  }else {
						  maps.put("code", -1);
						  maps.put("msg", "数据操作失败！");
					  }
				  }else {
						  SysRoleResourcePermissionBean bean = null;
						  if(parentId==0) {
							  List<SysResourceBean> list = sysResourceService.queryResource(nodeId);
							  for (SysResourceBean srb : list) {
								Integer resource=srb.getId();
								permissionBeans = permissionService.queryPermissionList(resource);
								for (SysPermissionBean permission : permissionBeans) {
									 Integer node=permission.getId();
									 Integer parent=resource;
									 bean = sysRoleresourcePerService.queryDataByRrp(roleId, parent, node);
									  if (bean==null) {
										  bean = new SysRoleResourcePermissionBean();
										  bean.setResourceId(parent);
										  bean.setPermissionId(node);
										  bean.setRoleId(Integer.parseInt(roleId));
										  HttpSession session=request.getSession();
										  Integer userId=(Integer) session.getAttribute("id");
										  bean.setCreateUser(userId);
										  bean.setCreateTime(new Date());
										  bean.setState(1);
										  count += sysRoleresourcePerService.saveData(bean);
									 }
							    }
							  }
						  }else{
							  if(parentId==1) {
									  permissionBeans = permissionService.queryPermissionList(nodeId);
									  for (SysPermissionBean permission : permissionBeans) {
										  Integer node=permission.getId();
										  Integer parent=nodeId;
										  bean = sysRoleresourcePerService.queryDataByRrp(roleId, parent, node);
										  if (bean==null) {
											  bean = new SysRoleResourcePermissionBean();
											  bean.setResourceId(parent);
											  bean.setPermissionId(node);
											  bean.setRoleId(Integer.parseInt(roleId));
											  HttpSession session=request.getSession();
											  Integer userId=(Integer) session.getAttribute("id");
											  bean.setCreateUser(userId);
											  bean.setCreateTime(new Date());
											  bean.setState(1);
											  count += sysRoleresourcePerService.saveData(bean);
										  }
									  }
							  }else {
								  bean = sysRoleresourcePerService.queryDataByRrp(roleId, parentId, nodeId);
								  if (bean==null) {
									  bean = new SysRoleResourcePermissionBean();
									  bean.setResourceId(parentId);
									  bean.setPermissionId(nodeId);
									  bean.setRoleId(Integer.parseInt(roleId));
									  HttpSession session=request.getSession();
									  Integer userId=(Integer) session.getAttribute("id");
									  bean.setCreateUser(userId);
									  bean.setCreateTime(new Date());
									  bean.setState(1);
									  count = sysRoleresourcePerService.saveData(bean);
								  }
							  }
						  }
					  if (count>0) {
						  maps.put("code", 1);
						  maps.put("msg", "角色授权成功！");
					  }else {
						  maps.put("code", -1);
						  maps.put("msg", "数据操作失败！");
					  }
				  }
			}
		   } catch (Exception e) {
			    log.error(e.getMessage());
			    maps.put("code", -1);
			    maps.put("msg", "数据异常，请稍后再试！");
		   }
		   return maps;
	   }
}